
// generator
const merge = require('lodash.merge')

function genBuilderConfig(opts) {
  return {
    build: {
      appId: opts.appId,
      productName: opts.productName,
      // files
      files: [
        '!src',
        '!public',
        `!${opts.srcDir}`
      ],
      // 扩展资源包 - 移动资源
      extraResources: [
        {
          from: `${opts.srcDir}`,
          to: '.',
          filter: ['**/*', '!icons', '!main-process']
        }
      ],
      win: {
        icon: `${opts.srcDir}/icons/icon.ico`,
        target: [
          {
            target: 'nsis',
            arch: ['x64']
          }
        ]
      }
    }
  }
}

module.exports = (api, options, rootOptions) => {
  const defConfig = require('../utils/defaultConfig');
  let _config = merge({}, defConfig, rootOptions, options);
  // package.json 命令配置
  api.extendPackage({
    main: `./${_config.outputDir}/main.electron.js`,
    scripts: {
      "ele_build": "vue-cli-service electron:build",
      "ele_dev": "vue-cli-service electron:serve",
      "ele_cls": "vue-cli-service electron:clean"
    },
    // 可能会出现重复
    build: null
  });
  // builder config
  api.extendPackage(genBuilderConfig(_config));
  // package 依赖
  api.extendPackage({
    devDependencies: {
      ...(options.eleVersion ? {'electron': _config.eleVersion} : {}),
      ...(options.eleVersion ? {'electron-builder': _config.eleBuilderVersion} : {}),
      ...(options.eleVersion ? {'electron-debug': _config.eleDebugVersion} : {}),
    }
  });
  
  // 渲染文件目录
  api.render('./template', _config);

  // 添加插件完成
  api.onCreateComplete(() => {
    const fs = require('fs-extra')
    // 更新 .gitignore 文件
    let ignorePath = api.resolve('./.gitignore')
    if(fs.existsSync(ignorePath)) {
      let ignore = fs.readFileSync(ignorePath, 'utf8')
      if(!/# Electron output|dist_\*/ig.test(ignore)) {
        ignore += '\r\n# Electron output\r\ndist_*\r\n'
        fs.writeFileSync(ignorePath, ignore)
      }
    }
  });
  
}
